package com.example.robotwatcher;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.example.robotwatcher.backend.VideoDecode;
import com.example.robotwatcher.backend.VideoReceiver;

import org.bytedeco.javacv.FFmpegFrameFilter;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;

public class VideoSurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable{
    //成员变量
    private SurfaceHolder mHolder;
    private Canvas mCanvas;//绘图的画布
    private boolean mIsDrawing;//控制绘画线程的标志位
    VideoReceiver receiver = new VideoReceiver();
    int FPS = 0;
    int frameID=0;
    long lastTime=0;
    String Path="rtsp://172.24.89.254/test";

    private Paint paint;//声明一个画笔


    public VideoSurfaceView(Context context)  {
        this(context,null);
    }

    public VideoSurfaceView(Context context, AttributeSet attr)  {
        this(context,attr,0);
    }

    public VideoSurfaceView(Context context,AttributeSet attr,int defStyleAttr)  {
        super(context,attr,defStyleAttr);
        init();
    }

    public void  init() {
        System.out.println("=================Start init==============");
        mHolder = getHolder();
        mHolder.addCallback(this);
        setFocusable(true);
        setKeepScreenOn(true);
        setFocusableInTouchMode(true);
        mIsDrawing = false;

        lastTime = System.nanoTime();

        paint = new Paint(Paint.FAKE_BOLD_TEXT_FLAG);
        paint.setColor(Color.RED);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.STROKE);
        paint.setTextSize(100);
        return;
    }

    void Start()
    {
        mIsDrawing = true;
        try {
            receiver.Init(Path);
            receiver.Start();

        } catch (FFmpegFrameGrabber.Exception e) {
            System.out.println("Get Flow Failed !!");
            mIsDrawing=false;
            e.printStackTrace();
        }
    }

    /// 获取RTSP流地址
    void setIPAddress(String IP)
    {
        Path = "rtsp://"+IP+"/test";
    }

    /// 重连按钮激活
    void RetryOnline()
    {

        try {
            receiver.Init(Path);
            mIsDrawing = true;
            Start();
            return;
        } catch (FFmpegFrameGrabber.Exception e) {
            System.out.println("Get Flow Failed !!");
//            mIsDrawing=false;
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void run() {
        while (true)
        {
            if(mIsDrawing){
                drawImage();
            }else {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                drawError();
            }

        }
    }
    private void drawError()
    {

        try {
            System.out.println("============drawError========");
            mCanvas = mHolder.lockCanvas();
//            mCanvas.drawCircle(50,50,30,paint);
//            mCanvas.drawCircle(10,10,20,paint);
            int width = mCanvas.getWidth();
            int height = 300;

            mCanvas.drawText("设备离线",width/2/2,200,paint);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mCanvas != null )
                mHolder.unlockCanvasAndPost(mCanvas);
        }


    }
    private void drawImage() {

        Frame frame = null;
        long currentTime = System.nanoTime();
        if((currentTime-lastTime)/1000000>1000)
        {
            FPS = frameID;
            frameID = 0;
            lastTime = currentTime;
        }
        Bitmap bmp;
        try {
            System.out.println("====================DrawImage============================="+FPS);
            frame = receiver.GetImage();
            if(frame==null) {mIsDrawing = false;throw new FFmpegFrameGrabber.Exception("Empty Frame");}
            bmp = VideoDecode.ConvertToBitmap(frame);
            frameID = frameID + 1;
            mCanvas = mHolder.lockCanvas();
            mCanvas.drawBitmap(bmp, null, new Rect(0, 0, mCanvas.getWidth(), frame.imageHeight * mCanvas.getWidth() / frame.imageWidth), null);
//            mHolder.unlockCanvasAndPost(canvas);
            // 输出尺寸
            System.out.println(frame.imageHeight * mCanvas.getWidth()/frame.imageWidth);
        }catch (FFmpegFrameGrabber.Exception e) {
            e.printStackTrace();
            mIsDrawing = false;
            System.out.println("FFmpegCatch Failed");
        }finally {
            try {
                if (mCanvas != null )
                    mHolder.unlockCanvasAndPost(mCanvas);
            }catch (Exception e){};


        }
// ===================测试验证SurfaceView是否被调用==========================
//        try {
//            System.out.println("============draw========");
//            mCanvas = mHolder.lockCanvas();
//            mCanvas.drawCircle(50,50,30,paint);
//            mCanvas.drawCircle(10,10,20,paint);
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (mCanvas != null)
//                mHolder.unlockCanvasAndPost(mCanvas);
//        }

    }
}
